<template>
  <div class="add-school-modal modal" v-if="visible">
    <div class="add-school">
      <div class="header">
        <span><i class="el-icon-school"></i> 添加学校</span>
        <i class="el-icon-close close-icon" @click="$emit('update:visible', false)"></i>
      </div>
      <div class="body">
        <div class="form-item">
          <span class="label"><i class="red">*</i>学校名称：</span>
          <el-input v-model="form.school_name" maxlength="50" placeholder="请输入学校名称"></el-input>
        </div>
        <div class="form-item">
          <span class="label"><i class="red">*</i>学段：</span>
          <el-select v-model="form.stage" placeholder="请选择学段">
            <el-option 
              v-for="item in stageList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="form-item">
          <span class="label"><i class="red">*</i>所在地区：</span>
          <div class="select-area">
            <el-select
              v-model="province"
              value-key="F_id"
              placeholder="省份"
              @change="changeProvince">
              <el-option
                v-for="item in provinceList"
                :key="item.F_id"
                :value="item"
                :label="item.F_name">
              </el-option>
            </el-select>
            <el-select
              v-model="city"
              value-key="F_id"
              placeholder="市"
              @change="changeCity">
              <el-option
                v-for="item in cityList"
                :key="item.F_id"
                :value="item"
                :label="item.F_name">
              </el-option>
            </el-select>
            <el-select
              v-model="district"
              value-key="F_id"
              placeholder="区（县）"
              @change="changeDistrict">
              <el-option
                v-for="item in districtList"
                :key="item.F_id"
                :value="item"
                :label="item.F_name">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <span class="label"><i class="red">*</i>管理员姓名：</span>
          <el-input v-model="form.admin_name" maxlength="20" placeholder="请输入管理员姓名"></el-input>
        </div>
        <div class="form-item">
          <span class="label"><i class="red">*</i>管理员手机：</span>
          <el-input 
            v-model="form.admin_phone" 
            maxlength="11" 
            placeholder="请输入管理员手机号"
            @input="validatePhone"
            @blur="validatePhoneOnBlur"
            @keypress="onlyAllowNumbers"
            :class="{ 'is-error': phoneError }"
          ></el-input>
          <span v-if="phoneError" class="error-message">{{ phoneError }}</span>
        </div>
        <div class="form-item">
          <span class="label"><i class="red">*</i>管理员性别：</span>
          <el-radio-group v-model="form.admin_gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="footer">
        <div class="btn-group">
          <el-button @click="$emit('update:visible', false)">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        school_name: '',
        stage: '',
        province_id: '',
        city_id: '',
        district_id: '',
        admin_name: '',
        admin_phone: '',
        admin_gender: 1,
        F_accesstoken: 'ny7FBMfXFtJgYdOVeUcsgA2twLBhpGQo'
      },
      areaId: 0,
      provinceList: [],
      cityList: [],
      districtList: [],
      province: {},
      city: {},
      district: {},
      stageList: [
        { id: '1', name: '小学' },
        { id: '2', name: '初中' },
        { id: '3', name: '高中' }
      ],
      phoneError: ''
    }
  },
  methods: {
    async submit() {
      // 表单验证
      if(!this.form.school_name) {
        return this.$toast('请输入学校名称')
      }
      if(!this.form.stage) {
        return this.$toast('请选择学段')
      }
      if(!this.areaId) {
        return this.$toast('请选择地区')
      }
      if(!this.form.admin_name) {
        return this.$toast('请输入管理员姓名')
      }
      if(!this.form.admin_phone) {
        return this.$toast('请输入管理员手机号')
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.form.admin_phone)) {
        this.phoneError = '手机号格式不正确';
        return this.$toast('请输入正确的手机号格式')
      }
      
      // 清除手机号错误提示
      this.phoneError = '';
      
      try {
        const res = await this.$api.createSchool(this.form)
        if(res.F_responseNo === 10000) {
          this.$toast('创建学校成功')
          this.$emit('success')
          this.$emit('update:visible', false)
        } else {
          this.$toast(res.F_responseMsg)
        }
      } catch(e) {
        console.error(e)
        this.$toast('创建学校失败')
      }
    },
    async changeProvince(val) {
      this.province = val;
      this.areaId = val.F_id;
      this.form.province_id = val.F_id;
      
      // 重置市和区
      this.cityList = [];
      this.districtList = [];
      this.city = {};
      this.district = {};
      this.form.city_id = '';
      this.form.district_id = '';
      
      // 获取市级数据
      if(val.F_id !== 0) {
        this.cityList = await this.getDistricts();
      }
    },
    
    async changeCity(val) {
      this.city = val;
      this.areaId = val.F_id;
      this.form.city_id = val.F_id;
      
      // 重置区
      this.districtList = [];
      this.district = {};
      this.form.district_id = '';
      
      // 获取区级数据
      if(val.F_id !== 0) {
        this.districtList = await this.getDistricts();
      }
    },
    
    changeDistrict(val) {
      this.district = val;
      this.areaId = val.F_id;
      this.form.district_id = val.F_id;
    },

    async getDistricts() {
      try {
        const res = await this.$api.getDistricts2({
          F_parent_id: this.areaId
        });
        if(res.F_responseNo === 10000) {
          return res.F_districts || [];
        } else {
          this.$toast('获取地区数据失败：' + res.F_responseMsg)
          return [];
        }
      } catch(e) {
        console.error(e)
        this.$toast('获取地区数据失败')
        return [];
      }
    },

    validatePhone() {
      const phone = this.form.admin_phone;
      
      // 只允许输入数字
      this.form.admin_phone = phone.replace(/\D/g, '');
      
      // 限制长度为11位
      if (this.form.admin_phone.length > 11) {
        this.form.admin_phone = this.form.admin_phone.slice(0, 11);
      }
      
      // 验证手机号格式
      if (this.form.admin_phone.length === 11) {
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(this.form.admin_phone)) {
          this.phoneError = '手机号格式不正确';
        } else {
          this.phoneError = '';
        }
      } else if (this.form.admin_phone.length > 0) {
        this.phoneError = '手机号必须是11位数字';
      } else {
        this.phoneError = '';
      }
    },

    validatePhoneOnBlur() {
      const phone = this.form.admin_phone;
      if (phone.length > 0 && phone.length !== 11) {
        this.phoneError = '手机号必须是11位数字';
      } else if (phone.length === 11) {
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(phone)) {
          this.phoneError = '手机号格式不正确';
        } else {
          this.phoneError = '';
        }
      } else {
        this.phoneError = '';
      }
    },

    onlyAllowNumbers(event) {
      const key = event.key;
      // 只允许数字键和功能键
      if (!/^\d$/.test(key) && !['Backspace', 'Delete', 'Tab', 'Enter', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(key)) {
        event.preventDefault();
      }
    }
  },
  async created() {
    // 获取省级数据
    this.provinceList = await this.getDistricts();
  }
}
</script>

<style lang="less" scoped>
.add-school-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(2px);

  .add-school {
    width: 550px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.2);
    animation: modalFadeIn 0.3s ease;

    .header {
      height: 56px;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      color: #303133;
      font-size: 18px;
      font-weight: 500;
      
      i.el-icon-school {
        color: #40DBBC;
        margin-right: 8px;
      }

      .close-icon {
        cursor: pointer;
        font-size: 20px;
        color: #909399;
        transition: color 0.3s;
        
        &:hover {
          color: #f56c6c;
        }
      }
    }

    .body {
      padding: 24px 30px;
      max-height: calc(80vh - 120px);
      overflow-y: auto;

      .form-item {
        margin-bottom: 22px;
        display: flex;
        align-items: center;

        .label {
          width: 120px;
          text-align: right;
          margin-right: 10px;
          color: #606266;
          font-size: 14px;

          .red {
            color: #f56c6c;
            margin-right: 4px;
          }
        }

        .el-input,
        .el-select,
        .el-cascader {
          width: 300px;
        }

        .select-area {
          width: 350px;
          display: flex;
          gap: 10px;
          
          .el-select {
            flex: 1;
          }
        }

        .error-message {
          margin-left: 10px;
          color: #f56c6c;
          font-size: 12px;
        }
        
        .is-error {
          .el-input__inner {
            border-color: #f56c6c !important;
            
            &:focus {
              border-color: #f56c6c !important;
            }
          }
        }
      }
    }

    .footer {
      padding: 16px 20px;
      text-align: right;
      border-top: 1px solid #ebeef5;
      
      .btn-group {
        .el-button {
          margin-left: 12px;
          padding: 9px 20px;
        }
      }
    }
  }
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 自定义滚动条 */
.body::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.body::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.body::-webkit-scrollbar-track {
  background-color: #f5f7fa;
  border-radius: 3px;
}
</style>

<style lang="less">
.add-school-modal {
  /* 优化输入框样式 */
  .el-input__inner {
    border-color: #dcdfe6;
    
    &:focus {
      border-color: #40DBBC;
    }
    
    &:hover {
      border-color: #c0c4cc;
    }
  }
  
  /* 优化单选按钮样式 */
  .el-radio__input.is-checked .el-radio__inner {
    background-color: #40DBBC;
    border-color: #40DBBC;
  }
  
  .el-radio__input.is-checked + .el-radio__label {
    color: #40DBBC;
  }
  
  /* 优化按钮样式 */
  .el-button--primary {
    background-color: #40DBBC;
    border-color: #40DBBC;
    
    &:hover, &:focus {
      background-color: #53e0c4;
      border-color: #53e0c4;
    }
  }
}
</style> 